package top.suven.base.http.admin.tools.dao;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
import top.suven.base.http.admin.tools.model.BuildCodeColumn;

import java.util.List;

/**
 * @ClassName:
 * @Description:
 * @Author lixiangling
 * @Date 2018/7/10 15:38
 * @Copyright: (c) 2018 gc by https://www.gc.com.cn/
 * @Version : 1.0.0
 * --------------------------------------------------------
 * modifyer    modifyTime                 comment
 *
 * --------------------------------------------------------
 */
@Component
public interface BuildCodeDao {
    @Select("select a.attname as column_name,col_description(a.attrelid,a.attnum) as column_comment,"+
            "a.atttypmod as length,b.typname as db_type,a.attnotnull AS notnull from "+
            "pg_class as c,pg_attribute as a,pg_type b where c.relname = #{tableName} and a.attrelid = c.oid and b.oid = a.atttypid and a.attnum>0")
    @Results(
            id="buildCode",
            value = {
                    @Result(column = "column_name" , property = "columnName"),
                    @Result(column = "column_comment" , property = "columnComment"),
                    @Result(column = "db_type" , property = "dbType"),
                    @Result(column = "notnull" , property = "isNotNull"),
                    @Result(column = "length" , property = "length")
            }
    )
    List<BuildCodeColumn> getBuildCodeByTableName(@Param("tableName") String tableName);

    @Select("select pg_attribute.attname as colname,pg_type.typname as typename,pg_constraint.conname as pk_name from "+
            "pg_constraint  inner join pg_class on pg_constraint.conrelid = pg_class.oid inner join pg_attribute on "+
            "pg_attribute.attrelid = pg_class.oid and  pg_attribute.attnum = pg_constraint.conkey[1] "+
            "inner join pg_type on pg_type.oid = pg_attribute.atttypid where pg_class.relname = #{tableName} "+
            "and pg_constraint.contype='p'")
    List<String> getPKName(@Param("tableName") String tableName);
}
